package demo.servicemix.cxf;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Response;

@Path("/bookService/")
public class BookService {
	private static AtomicInteger nextId = new AtomicInteger(0);
	private Map<String, Book> bookCache = new ConcurrentHashMap<String, Book>();

	@GET
	@Path("/books/{id}/")
	public Book getBook(@PathParam("id") String id) {
		return bookCache.get(id);
	}
	
	@GET
	@Path("/books/")
	public List<Book> listBook(@QueryParam("author") String author) {
		List<Book> bookList = new ArrayList<Book>();
		for(Book book : bookCache.values()){
			if(author == null || author.trim().length() ==0 || author.trim().equals(book.getAuthor())){
				bookList.add(book);
			}
		}
		return bookList;
	}

	@POST
	@Path("/books/")
	public Response addBook(Book book) {
		book.setId(nextId.incrementAndGet());
		book.setUpdateDate(new Date());
		bookCache.put(String.valueOf(book.getId()), book);
		return Response.ok().type("application/xml").entity(book).build();
	}

	@PUT
	@Path("/books/")
	public Response updateBook(Book book) {
		Book oldBook = bookCache.get(String.valueOf(book.getId()));
		if (oldBook == null) {
			return Response.notModified().build();
		} else {
			oldBook.setAuthor(book.getAuthor());
			oldBook.setName(book.getName());
			oldBook.setUpdateDate(new Date());
			return Response.ok().build();
		}
	}

	@DELETE
	@Path("/books/{id}/")
	public Response deleteBook(@PathParam("id") String id) {
		Book book = bookCache.remove(id);
		if (book != null) {
			return Response.ok().build();
		} else {
			return Response.notModified().build();
		}
	}
}
